#include "ChannelConfigDialog.h"
#include "CollectorConfigDialog.h"
#include "ServerConfigDialog.h"
#include "DataMonitorWidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QFormLayout>
#include <QGroupBox>
#include <QHeaderView>
#include <QMessageBox>
#include <QPushButton>
#include <QDialogButtonBox>
#include <QSplitter>
#include <QJsonArray>
#include <QDebug>
#include <QSizePolicy>

namespace ModbusPlexLink {

ChannelConfigDialog::ChannelConfigDialog(Channel* channel,
                                         ChannelManager* channelManager,
                                         QWidget *parent)
    : QDialog(parent)
    , m_channel(channel)
    , m_channelManager(channelManager)
    , m_isNewChannel(channel == nullptr)
    , m_tabWidget(nullptr)
    , m_nameEdit(nullptr)
    , m_enabledCheck(nullptr)
    , m_descriptionEdit(nullptr)
    , m_collectorTable(nullptr)
    , m_addCollectorBtn(nullptr)
    , m_editCollectorBtn(nullptr)
    , m_deleteCollectorBtn(nullptr)
    , m_collectorCountLabel(nullptr)
    , m_serverTable(nullptr)
    , m_addServerBtn(nullptr)
    , m_editServerBtn(nullptr)
    , m_deleteServerBtn(nullptr)
    , m_serverCountLabel(nullptr)
    , m_dataMonitorWidget(nullptr)
    , m_monitorInfoLabel(nullptr)
{
    setWindowTitle(m_isNewChannel ? tr("新建通道") : tr("编辑通道"));
    resize(900, 700);
    setMinimumSize(800, 600);
    
    setupUi();
    loadConfig();
    
    // 新建通道时，设置默认名称
    if (m_isNewChannel) {
        m_nameEdit->setText(tr("新通道"));
        m_nameEdit->selectAll();
        m_nameEdit->setFocus();
    }
}

ChannelConfigDialog::~ChannelConfigDialog() {
}

void ChannelConfigDialog::setupUi() {
    QVBoxLayout* mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(10, 10, 10, 10);
    
    // Tab页签
    m_tabWidget = new QTabWidget(this);
    
    createBasicInfoTab();
    createCollectorTab();
    createServerTab();
    createMonitorTab();
    
    mainLayout->addWidget(m_tabWidget);
    
    // 底部按钮
    QDialogButtonBox* buttonBox = new QDialogButtonBox(
        QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
    
    connect(buttonBox, &QDialogButtonBox::accepted, this, &ChannelConfigDialog::onAccepted);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &ChannelConfigDialog::onRejected);
    
    mainLayout->addWidget(buttonBox);
}

void ChannelConfigDialog::createBasicInfoTab() {
    QWidget* basicTab = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(basicTab);
    layout->setContentsMargins(20, 20, 20, 20);
    layout->setSpacing(15);
    
    // 标题
    QLabel* titleLabel = new QLabel(tr("通道基本信息"), basicTab);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(11);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    layout->addWidget(titleLabel);
    
    // 表单
    QFormLayout* formLayout = new QFormLayout();
    formLayout->setLabelAlignment(Qt::AlignRight | Qt::AlignVCenter);
    formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
    formLayout->setHorizontalSpacing(15);
    formLayout->setVerticalSpacing(12);
    
    // 通道名称
    m_nameEdit = new QLineEdit(basicTab);
    m_nameEdit->setPlaceholderText(tr("请输入通道名称（唯一标识）"));
    m_nameEdit->setMaxLength(64);
    connect(m_nameEdit, &QLineEdit::textChanged, this, &ChannelConfigDialog::onNameChanged);
    
    QLabel* nameLabel = new QLabel(tr("通道名称*:"), basicTab);
    formLayout->addRow(nameLabel, m_nameEdit);
    
    // 启用状态
    m_enabledCheck = new QCheckBox(tr("启用此通道"), basicTab);
    m_enabledCheck->setChecked(true);
    formLayout->addRow(tr("启用状态:"), m_enabledCheck);
    
    layout->addLayout(formLayout);
    
    // 描述
    QLabel* descLabel = new QLabel(tr("描述信息:"), basicTab);
    layout->addWidget(descLabel);
    
    m_descriptionEdit = new QTextEdit(basicTab);
    m_descriptionEdit->setPlaceholderText(tr("可选：输入通道的详细描述信息"));
    m_descriptionEdit->setMaximumHeight(100);
    layout->addWidget(m_descriptionEdit);
    
    // 说明文字
    QLabel* hintLabel = new QLabel(
        tr("<i>提示：通道是数据采集和转发的独立单元，每个通道拥有独立的数据缓存(UDM)。</i>"),
        basicTab);
    hintLabel->setWordWrap(true);
    hintLabel->setStyleSheet("color: #666; padding: 10px;");
    layout->addWidget(hintLabel);
    
    layout->addStretch();
    
    m_tabWidget->addTab(basicTab, tr("基本信息"));
}

void ChannelConfigDialog::createCollectorTab() {
    QWidget* collectorTab = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(collectorTab);
    layout->setContentsMargins(10, 10, 10, 10);
    layout->setSpacing(10);
    
    // 标题和说明
    QHBoxLayout* headerLayout = new QHBoxLayout();
    
    QLabel* titleLabel = new QLabel(tr("采集器列表"), collectorTab);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(11);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    headerLayout->addWidget(titleLabel);
    
    headerLayout->addStretch();
    
    m_collectorCountLabel = new QLabel(tr("采集器数量: 0"), collectorTab);
    m_collectorCountLabel->setStyleSheet("color: #666;");
    headerLayout->addWidget(m_collectorCountLabel);
    
    layout->addLayout(headerLayout);
    
    // 说明
    QLabel* hintLabel = new QLabel(
        tr("采集器从物理设备读取数据并写入UDM。支持配置IP地址、端口、轮询间隔和映射规则。"),
        collectorTab);
    hintLabel->setWordWrap(true);
    hintLabel->setStyleSheet("color: #666; padding: 5px;");
    layout->addWidget(hintLabel);
    
    // 采集器表格
    m_collectorTable = new QTableWidget(collectorTab);
    m_collectorTable->setColumnCount(6);
    m_collectorTable->setHorizontalHeaderLabels({
        tr("名称"), tr("IP地址"), tr("端口"), tr("从站ID"), 
        tr("轮询间隔(ms)"), tr("映射数量")
    });
    
    m_collectorTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_collectorTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_collectorTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_collectorTable->setAlternatingRowColors(true);
    m_collectorTable->verticalHeader()->setVisible(false);
    m_collectorTable->horizontalHeader()->setStretchLastSection(true);
    m_collectorTable->setColumnWidth(0, 150);
    m_collectorTable->setColumnWidth(1, 120);
    m_collectorTable->setColumnWidth(2, 80);
    m_collectorTable->setColumnWidth(3, 80);
    m_collectorTable->setColumnWidth(4, 100);
    
    connect(m_collectorTable, &QTableWidget::itemSelectionChanged,
            this, &ChannelConfigDialog::onCollectorTableSelectionChanged);
    connect(m_collectorTable, &QTableWidget::cellDoubleClicked,
            this, &ChannelConfigDialog::onCollectorTableDoubleClicked);
    
    layout->addWidget(m_collectorTable);
    
    // 操作按钮
    QHBoxLayout* btnLayout = new QHBoxLayout();
    
    m_addCollectorBtn = new QPushButton(tr("添加采集器"), collectorTab);
    m_editCollectorBtn = new QPushButton(tr("编辑采集器"), collectorTab);
    m_deleteCollectorBtn = new QPushButton(tr("删除采集器"), collectorTab);
    
    m_addCollectorBtn->setMinimumWidth(100);
    m_editCollectorBtn->setMinimumWidth(100);
    m_deleteCollectorBtn->setMinimumWidth(100);
    
    connect(m_addCollectorBtn, &QPushButton::clicked, this, &ChannelConfigDialog::onAddCollector);
    connect(m_editCollectorBtn, &QPushButton::clicked, this, &ChannelConfigDialog::onEditCollector);
    connect(m_deleteCollectorBtn, &QPushButton::clicked, this, &ChannelConfigDialog::onDeleteCollector);
    
    btnLayout->addWidget(m_addCollectorBtn);
    btnLayout->addWidget(m_editCollectorBtn);
    btnLayout->addWidget(m_deleteCollectorBtn);
    btnLayout->addStretch();
    
    layout->addLayout(btnLayout);
    
    m_tabWidget->addTab(collectorTab, tr("采集器"));
    
    updateCollectorButtons();
}

void ChannelConfigDialog::createServerTab() {
    QWidget* serverTab = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(serverTab);
    layout->setContentsMargins(10, 10, 10, 10);
    layout->setSpacing(10);
    
    // 标题和说明
    QHBoxLayout* headerLayout = new QHBoxLayout();
    
    QLabel* titleLabel = new QLabel(tr("服务器列表"), serverTab);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(11);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    headerLayout->addWidget(titleLabel);
    
    headerLayout->addStretch();
    
    m_serverCountLabel = new QLabel(tr("服务器数量: 0"), serverTab);
    m_serverCountLabel->setStyleSheet("color: #666;");
    headerLayout->addWidget(m_serverCountLabel);
    
    layout->addLayout(headerLayout);
    
    // 说明
    QLabel* hintLabel = new QLabel(
        tr("服务器监听客户端连接，从UDM读取数据并响应。每个服务器可包含多个虚拟设备。"),
        serverTab);
    hintLabel->setWordWrap(true);
    hintLabel->setStyleSheet("color: #666; padding: 5px;");
    layout->addWidget(hintLabel);
    
    // 服务器表格
    m_serverTable = new QTableWidget(serverTab);
    m_serverTable->setColumnCount(5);
    m_serverTable->setHorizontalHeaderLabels({
        tr("名称"), tr("监听地址"), tr("端口"), 
        tr("虚拟设备数"), tr("状态")
    });
    
    m_serverTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_serverTable->setSelectionMode(QAbstractItemView::SingleSelection);
    m_serverTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_serverTable->setAlternatingRowColors(true);
    m_serverTable->verticalHeader()->setVisible(false);
    m_serverTable->horizontalHeader()->setStretchLastSection(true);
    m_serverTable->setColumnWidth(0, 150);
    m_serverTable->setColumnWidth(1, 120);
    m_serverTable->setColumnWidth(2, 80);
    m_serverTable->setColumnWidth(3, 100);
    
    connect(m_serverTable, &QTableWidget::itemSelectionChanged,
            this, &ChannelConfigDialog::onServerTableSelectionChanged);
    connect(m_serverTable, &QTableWidget::cellDoubleClicked,
            this, &ChannelConfigDialog::onServerTableDoubleClicked);
    
    layout->addWidget(m_serverTable);
    
    // 操作按钮
    QHBoxLayout* btnLayout = new QHBoxLayout();
    
    m_addServerBtn = new QPushButton(tr("添加服务器"), serverTab);
    m_editServerBtn = new QPushButton(tr("编辑服务器"), serverTab);
    m_deleteServerBtn = new QPushButton(tr("删除服务器"), serverTab);
    
    m_addServerBtn->setMinimumWidth(100);
    m_editServerBtn->setMinimumWidth(100);
    m_deleteServerBtn->setMinimumWidth(100);
    
    connect(m_addServerBtn, &QPushButton::clicked, this, &ChannelConfigDialog::onAddServer);
    connect(m_editServerBtn, &QPushButton::clicked, this, &ChannelConfigDialog::onEditServer);
    connect(m_deleteServerBtn, &QPushButton::clicked, this, &ChannelConfigDialog::onDeleteServer);
    
    btnLayout->addWidget(m_addServerBtn);
    btnLayout->addWidget(m_editServerBtn);
    btnLayout->addWidget(m_deleteServerBtn);
    btnLayout->addStretch();
    
    layout->addLayout(btnLayout);
    
    m_tabWidget->addTab(serverTab, tr("服务器"));
    
    updateServerButtons();
}

void ChannelConfigDialog::createMonitorTab() {
    QWidget* monitorTab = new QWidget();
    QVBoxLayout* layout = new QVBoxLayout(monitorTab);
    layout->setContentsMargins(20, 20, 20, 20);
    layout->setSpacing(12);
    
    // 标题
    QLabel* titleLabel = new QLabel(tr("数据监控（预览）"), monitorTab);
    QFont titleFont = titleLabel->font();
    titleFont.setPointSize(11);
    titleFont.setBold(true);
    titleLabel->setFont(titleFont);
    layout->addWidget(titleLabel);
    
    // 信息标签
    QString infoText;
    if (m_channel && m_channelManager) {
        infoText = tr("实时预览当前通道的UDM数据，便于核对映射与报警规则。");
    } else {
        infoText = tr("保存并启动通道后，可在此页快速查看对应通道的实时数据。");
    }

    m_monitorInfoLabel = new QLabel(infoText, monitorTab);
    m_monitorInfoLabel->setStyleSheet("color: #666; padding: 10px; background: #f5f5f5; border-radius: 4px;");
    m_monitorInfoLabel->setWordWrap(true);
    layout->addWidget(m_monitorInfoLabel);
    
    const bool canPreview = (m_channelManager != nullptr && m_channel != nullptr);
    if (canPreview) {
        m_dataMonitorWidget = new DataMonitorWidget(m_channelManager, monitorTab);
        m_dataMonitorWidget->setChannel(m_channel);
        m_dataMonitorWidget->setMinimumHeight(320);
        layout->addWidget(m_dataMonitorWidget, 1);
    } else {
        QLabel* placeholderLabel = new QLabel(
            tr("暂无实时数据可展示。\n请保存配置并在主界面启动通道后再查看。"),
            monitorTab);
        placeholderLabel->setAlignment(Qt::AlignCenter);
        placeholderLabel->setStyleSheet(
            "color: #999;"
            "border: 1px dashed #ccc;"
            "border-radius: 6px;"
            "padding: 40px;");
        placeholderLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        layout->addWidget(placeholderLabel, 1);
    }
    
    m_tabWidget->addTab(monitorTab, tr("数据监控"));
}

void ChannelConfigDialog::loadConfig() {
    if (m_channel) {
        m_config = m_channel->getConfig();
        
        // 加载基本信息
        m_nameEdit->setText(m_config.name);
        m_nameEdit->setEnabled(false);  // 编辑模式下不允许修改名称
        m_enabledCheck->setChecked(m_config.enabled);
        
        // 加载采集器和服务器配置
        m_collectors = m_config.collectors;
        m_servers = m_config.servers;
    } else {
        // 新建通道，使用默认值
        m_config.enabled = true;
    }
    
    refreshCollectorTable();
    refreshServerTable();
}

bool ChannelConfigDialog::validateConfig() {
    // 验证通道名称
    QString name = m_nameEdit->text().trimmed();
    if (name.isEmpty()) {
        QMessageBox::warning(this, tr("验证失败"), tr("通道名称不能为空"));
        m_tabWidget->setCurrentIndex(0);
        m_nameEdit->setFocus();
        return false;
    }
    
    // 验证是否至少有一个采集器
    if (m_collectors.isEmpty()) {
        QMessageBox::StandardButton reply = QMessageBox::question(
            this, tr("确认"),
            tr("当前没有配置采集器，通道将无法采集数据。\n是否继续？"),
            QMessageBox::Yes | QMessageBox::No);
        
        if (reply == QMessageBox::No) {
            m_tabWidget->setCurrentIndex(1);
            return false;
        }
    }
    
    // 验证是否至少有一个服务器
    if (m_servers.isEmpty()) {
        QMessageBox::StandardButton reply = QMessageBox::question(
            this, tr("确认"),
            tr("当前没有配置服务器，通道将无法对外提供数据。\n是否继续？"),
            QMessageBox::Yes | QMessageBox::No);
        
        if (reply == QMessageBox::No) {
            m_tabWidget->setCurrentIndex(2);
            return false;
        }
    }
    
    return true;
}

ChannelConfig ChannelConfigDialog::getConfig() const {
    ChannelConfig config;
    config.name = m_nameEdit->text().trimmed();
    config.enabled = m_enabledCheck->isChecked();
    config.collectors = m_collectors;
    config.servers = m_servers;
    return config;
}

void ChannelConfigDialog::setConfig(const ChannelConfig& config) {
    m_config = config;
    loadConfig();
}

void ChannelConfigDialog::refreshCollectorTable() {
    m_collectorTable->setRowCount(0);
    m_collectorTable->setRowCount(m_collectors.size());
    
    for (int i = 0; i < m_collectors.size(); ++i) {
        QJsonObject collector = m_collectors[i];
        
        // 名称
        QTableWidgetItem* nameItem = new QTableWidgetItem(
            collector.value("name").toString());
        m_collectorTable->setItem(i, 0, nameItem);
        
        // IP地址
        QTableWidgetItem* ipItem = new QTableWidgetItem(
            collector.value("ip").toString());
        ipItem->setTextAlignment(Qt::AlignCenter);
        m_collectorTable->setItem(i, 1, ipItem);
        
        // 端口
        QTableWidgetItem* portItem = new QTableWidgetItem(
            QString::number(collector.value("port").toInt()));
        portItem->setTextAlignment(Qt::AlignCenter);
        m_collectorTable->setItem(i, 2, portItem);
        
        // 从站ID
        QTableWidgetItem* unitIdItem = new QTableWidgetItem(
            QString::number(collector.value("unitId").toInt()));
        unitIdItem->setTextAlignment(Qt::AlignCenter);
        m_collectorTable->setItem(i, 3, unitIdItem);
        
        // 轮询间隔
        QTableWidgetItem* pollRateItem = new QTableWidgetItem(
            QString::number(collector.value("pollRate").toInt()));
        pollRateItem->setTextAlignment(Qt::AlignCenter);
        m_collectorTable->setItem(i, 4, pollRateItem);
        
        // 映射数量
        int mappingCount = collector.value("mappings").toArray().size();
        QTableWidgetItem* mappingCountItem = new QTableWidgetItem(
            QString::number(mappingCount));
        mappingCountItem->setTextAlignment(Qt::AlignCenter);
        m_collectorTable->setItem(i, 5, mappingCountItem);
    }
    
    m_collectorCountLabel->setText(tr("采集器数量: %1").arg(m_collectors.size()));
    updateCollectorButtons();
}

void ChannelConfigDialog::refreshServerTable() {
    m_serverTable->setRowCount(0);
    m_serverTable->setRowCount(m_servers.size());
    
    for (int i = 0; i < m_servers.size(); ++i) {
        QJsonObject server = m_servers[i];
        
        // 名称
        QTableWidgetItem* nameItem = new QTableWidgetItem(
            server.value("name").toString());
        m_serverTable->setItem(i, 0, nameItem);
        
        // 监听地址
        QTableWidgetItem* listenItem = new QTableWidgetItem(
            server.value("listenAddress").toString("0.0.0.0"));
        listenItem->setTextAlignment(Qt::AlignCenter);
        m_serverTable->setItem(i, 1, listenItem);
        
        // 端口
        QTableWidgetItem* portItem = new QTableWidgetItem(
            QString::number(server.value("port").toInt()));
        portItem->setTextAlignment(Qt::AlignCenter);
        m_serverTable->setItem(i, 2, portItem);
        
        // 虚拟设备数量
        int vdCount = server.value("virtualDevices").toArray().size();
        QTableWidgetItem* vdCountItem = new QTableWidgetItem(
            QString::number(vdCount));
        vdCountItem->setTextAlignment(Qt::AlignCenter);
        m_serverTable->setItem(i, 3, vdCountItem);
        
        // 状态
        QTableWidgetItem* statusItem = new QTableWidgetItem(tr("已配置"));
        statusItem->setTextAlignment(Qt::AlignCenter);
        statusItem->setForeground(QBrush(QColor(100, 100, 100)));
        m_serverTable->setItem(i, 4, statusItem);
    }
    
    m_serverCountLabel->setText(tr("服务器数量: %1").arg(m_servers.size()));
    updateServerButtons();
}

int ChannelConfigDialog::getSelectedCollectorRow() const {
    QList<QTableWidgetItem*> selected = m_collectorTable->selectedItems();
    if (selected.isEmpty()) {
        return -1;
    }
    return selected.first()->row();
}

int ChannelConfigDialog::getSelectedServerRow() const {
    QList<QTableWidgetItem*> selected = m_serverTable->selectedItems();
    if (selected.isEmpty()) {
        return -1;
    }
    return selected.first()->row();
}

void ChannelConfigDialog::updateCollectorButtons() {
    bool hasSelection = getSelectedCollectorRow() >= 0;
    m_editCollectorBtn->setEnabled(hasSelection);
    m_deleteCollectorBtn->setEnabled(hasSelection);
}

void ChannelConfigDialog::updateServerButtons() {
    bool hasSelection = getSelectedServerRow() >= 0;
    m_editServerBtn->setEnabled(hasSelection);
    m_deleteServerBtn->setEnabled(hasSelection);
}

// ============= 槽函数实现 =============

void ChannelConfigDialog::onNameChanged(const QString& text) {
    Q_UNUSED(text);
    // 实时验证可以在这里添加
}

void ChannelConfigDialog::onAddCollector() {
    CollectorConfigDialog dialog(QJsonObject(), this);
    dialog.setWindowTitle(tr("新建采集器"));
    
    if (dialog.exec() == QDialog::Accepted) {
        QJsonObject config = dialog.getConfig();
        m_collectors.append(config);
        refreshCollectorTable();
    }
}

void ChannelConfigDialog::onEditCollector() {
    int row = getSelectedCollectorRow();
    if (row < 0 || row >= m_collectors.size()) {
        return;
    }
    
    CollectorConfigDialog dialog(m_collectors[row], this);
    dialog.setWindowTitle(tr("编辑采集器 - %1")
        .arg(m_collectors[row].value("name").toString()));
    
    if (dialog.exec() == QDialog::Accepted) {
        QJsonObject config = dialog.getConfig();
        m_collectors[row] = config;
        refreshCollectorTable();
    }
}

void ChannelConfigDialog::onDeleteCollector() {
    int row = getSelectedCollectorRow();
    if (row < 0 || row >= m_collectors.size()) {
        return;
    }
    
    QString collectorName = m_collectors[row].value("name").toString();
    
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, tr("确认删除"),
        tr("确定要删除采集器 '%1' 吗？").arg(collectorName),
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        m_collectors.removeAt(row);
        refreshCollectorTable();
    }
}

void ChannelConfigDialog::onCollectorTableSelectionChanged() {
    updateCollectorButtons();
}

void ChannelConfigDialog::onCollectorTableDoubleClicked(int row, int column) {
    Q_UNUSED(column);
    if (row >= 0) {
        onEditCollector();
    }
}

void ChannelConfigDialog::onAddServer() {
    ServerConfigDialog dialog(QJsonObject(), this);
    dialog.setWindowTitle(tr("新建服务器"));

    if (dialog.exec() == QDialog::Accepted) {
        QJsonObject config = dialog.getConfig();
        m_servers.append(config);
        refreshServerTable();
    }
}

void ChannelConfigDialog::onEditServer() {
    int row = getSelectedServerRow();
    if (row < 0 || row >= m_servers.size()) {
        return;
    }

    ServerConfigDialog dialog(m_servers[row], this);
    dialog.setWindowTitle(tr("编辑服务器 - %1")
        .arg(m_servers[row].value("name").toString()));

    if (dialog.exec() == QDialog::Accepted) {
        QJsonObject config = dialog.getConfig();
        m_servers[row] = config;
        refreshServerTable();
    }
}

void ChannelConfigDialog::onDeleteServer() {
    int row = getSelectedServerRow();
    if (row < 0 || row >= m_servers.size()) {
        return;
    }
    
    QString serverName = m_servers[row].value("name").toString();
    
    QMessageBox::StandardButton reply = QMessageBox::question(
        this, tr("确认删除"),
        tr("确定要删除服务器 '%1' 吗？").arg(serverName),
        QMessageBox::Yes | QMessageBox::No);
    
    if (reply == QMessageBox::Yes) {
        m_servers.removeAt(row);
        refreshServerTable();
    }
}

void ChannelConfigDialog::onServerTableSelectionChanged() {
    updateServerButtons();
}

void ChannelConfigDialog::onServerTableDoubleClicked(int row, int column) {
    Q_UNUSED(column);
    if (row >= 0) {
        onEditServer();
    }
}

void ChannelConfigDialog::onAccepted() {
    if (validateConfig()) {
        accept();
    }
}

void ChannelConfigDialog::onRejected() {
    reject();
}

} // namespace ModbusPlexLink
